<template>
	<div class="form-control">
		<el-form :model="localGroup" label-width="auto">
			<el-form-item label="组名称">
				<el-input
					v-model="localGroup.name"
					type="text"
					placeholder="请输入人员组名称"
				/>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="handleSubmit">保存</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>


<script>
export default {
  props: {
    groupName: String,
    groupId: Number,
  },
  data() {
    return {
      localGroup: {
        name: '',
        id: null,
      },
    };
  },
  watch: {
    groupName: {
      immediate: true,
      handler(newVal) {
        this.localGroup.name = newVal || '';
      },
    },
    groupId: {
      immediate: true,
      handler(newVal) {
        this.localGroup.id = newVal || null;
      },
    },
  },
  methods: {
    async handleSubmit() {
      try {
        if (this.localGroup.id) {
          await this.$api.updateGroup(this.localGroup.id, { name: this.localGroup.name });
          this.$message.success('更新成功');
        } else {
          await this.$api.groupAdd({ name: this.localGroup.name });
          this.$message.success('添加成功');
        }

        // 清空本地表单数据
        this.localGroup = { name: '', id: null };

        // 通知父组件清空 prop，避免 watch 再次写回旧值
        this.$emit('clear');

        // 通知父组件刷新列表
        this.$emit('success');
      } catch (err) {
        this.$message.error(this.localGroup.id ? '更新失败' : '添加失败');
        console.error("更新失败错误信息：", err);
      }
    },
  },
};
</script>



<style scoped>
.form-control {
  padding: 30px 30px 10px;
}
</style>
